package csu.web.credit_bank.intercepter;
import csu.web.credit_bank.utils.JwtHelper;
import csu.web.credit_bank.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import java.io.IOException;
import java.io.PrintWriter;
//意味着在前端页面除了登录和注册外都需要在页面显示是利用js来向后端发送请求，判断用户令牌是否有效，如果有效则显示页面，否则跳转到登录页面。
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean preHandle(jakarta.servlet.http.HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
           // sendError(response, HttpServletResponse.SC_UNAUTHORIZED, "缺少或无效的Token");
            Result result = Result.failure(1, "缺少或无效的Token");
            returnJson(response, result);
            return false;
        }

        String token = authHeader.substring(7);
        try {
            // 解析Token并验证有效性
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtHelper.getTokenSignKey())
                    .parseClaimsJws(token)
                    .getBody();

            // 获取用户ID并存储到请求中
//            Long userId = ((Number) claims.get("userId")).longValue();
//            request.setAttribute("userId", userId);
            return true;
        } catch (ExpiredJwtException e) {

            Result result = Result.failure(401, "Token已过期");
            returnJson(response, result);
            return false;


        } catch (JwtException | IllegalArgumentException e) {
            // 其他异常，如签名验证失败等
            Result result = Result.failure(401, "Token解析失败");
            returnJson(response, result);

            return false;
        }
    }
    private void returnJson(HttpServletResponse response, Result result) throws Exception {
        if (objectMapper == null) {
            throw new IllegalStateException("objectMapper is not initialized");
        }
        String json = objectMapper.writeValueAsString(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (IOException e) {
            // 使用日志记录异常
            e.printStackTrace();
            // 或者重新抛出异常，让调用者处理
            throw e;
        }
    }
}
